<template>
  <el-config-provider :locale="zhCn">
    <div class="loss-customer-container">
      <!-- 筛选条件区域 -->
      <filter-form v-model="filterForm" :form-items="formItems" @search="handleSearch" @reset="resetFilter" @update:modelValue="handleFilterChange" />

      <!-- 选项卡区域 -->
      <el-tabs v-model="activeTab" type="card" class="notice-tabs" @tab-click="handleTabClick">
        <!-- 客户列表 -->
        <el-tab-pane label="客户列表" name="lossCustomer">
          <div class="table-section">
            <div class="operation-section">
              <el-button type="primary" :disabled="!selectedCustomers.length" @click="handleBatchActivateUser">批量激活用户</el-button>
              <span style="margin-left: 16px; color: #f56c6c; font-size: 14px; vertical-align: middle">超过15天未联系</span>
            </div>
            <el-table
              :data="customerList"
              border
              style="width: 100%"
              v-loading="loading"
              class="custom-table"
              ref="customerTableRef"
              @selection-change="onCustomerSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column label="客户信息" min-width="220">
                <template #default="scope">
                  <AiWechatInfo :avatar-url="scope.row.sendWxUser?.userAvatarUrl" :user-name="scope.row.sendWxUser?.userName" />
                </template>
              </el-table-column>
              <el-table-column prop="lastMessage" label="最后消息" min-width="160" />
              <el-table-column prop="lastMessageTime" label="最后消息时间" min-width="160" />
              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button type="primary" link @click="handleSingleActivate(scope.row)">激活</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 日志列表 -->
        <el-tab-pane label="日志" name="activationLog">
          <div class="table-section">
            <el-table :data="logList" border style="width: 100%" v-loading="loading" class="custom-table">
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="sendWxNames" label="客户信息" min-width="180">
                <template #default="scope">
                  <div v-if="Array.isArray(scope.row.sendWxList) && scope.row.sendWxList.length">
                    <div v-for="(wx, idx) in scope.row.sendWxList" :key="idx" style="margin-bottom: 4px">
                      <AiWechatInfo :avatar-url="wx.userUrl" :user-name="wx.userName" />
                    </div>
                  </div>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" min-width="100">
                <template #default="scope">
                  <el-tag v-if="scope.row.status === '1'" type="success">已完成</el-tag>
                  <span v-else>{{ scope.row.status }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="executionTime" label="执行时间" min-width="160" />
              <el-table-column prop="createByStr" label="创建人" min-width="120" />
              <el-table-column prop="createTime" label="创建时间" min-width="160" />
              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button type="primary" link @click="showLogMessagePreview(scope.row)">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 模板 -->
        <el-tab-pane label="模板" name="template">
          <div class="table-section">
            <div class="operation-section">
              <el-button type="primary" @click="handleAddTask">新增模板</el-button>
            </div>
            <el-table :data="templateList" border style="width: 100%" v-loading="loading" class="custom-table">
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="template_name" label="模板名称" min-width="150" />
              <el-table-column label="消息类型" width="200" align="center">
                <template #default="scope">
                  <div class="message-type-tags">
                    <el-tag v-for="(type, idx) in getMessageTypes(scope.row)" :key="idx" :type="getMessageTypeTag(type)" class="message-type-tag">
                      {{ getMessageTypeText(type) }}
                    </el-tag>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150">
                <template #default="scope">
                  <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
                  <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>

      <!-- 分页 -->
      <pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total" @pagination="handlePagination" />

      <!-- 精准群发任务编辑对话框 -->
      <el-dialog
        v-model="editTaskDialogVisible"
        :title="isActivateMode ? '激活流失用户' : currentTask.taskId ? (currentTask.status === '2' ? '查看模板' : '编辑模板') : '新增模板'"
        width="90%"
        destroy-on-close
        class="task-dialog"
      >
        <div style="display: flex; gap: 80px; height: 83vh; overflow: hidden">
          <div style="width: 70%; height: 100%; display: flex; flex-direction: column; overflow: hidden">
            <el-form :model="editTaskForm" label-width="100px" class="task-form">
              <el-form-item label="模板名称" required v-if="!isActivateMode">
                <el-input v-model="editTaskForm.taskName" placeholder="请输入模板名称" :disabled="currentTask.status === '2'" />
              </el-form-item>
              <el-form-item label="选择模板" v-if="isActivateMode">
                <el-select v-model="selectedTemplateId" placeholder="请选择模板" clearable @change="handleTemplateSelect">
                  <el-option v-for="template in templateList" :key="template.template_id" :label="template.template_name" :value="template.template_id" />
                </el-select>
              </el-form-item>
              <el-form-item label="发送对象" required class="task-dialog-send" v-if="isActivateMode">
                <div class="target-section">
                  <div class="target-preview" v-if="editTaskForm.friends.length">
                    <div class="target-group">
                      <!-- <div class="target-label">已选好友：</div> -->
                      <div class="target-list">
                        <el-tag
                          v-for="friend in editTaskForm.friends"
                          :key="friend.id"
                          :closable="currentTask.status !== '2'"
                          @close="handleRemoveFriend(friend)"
                          class="target-item"
                          :class="{ 'is-disabled': currentTask.status === '2' }"
                        >
                          {{ friend.nick_name }}
                        </el-tag>
                      </div>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </el-form>
            <div class="selectSend">
              <div class="section-title">内容类型</div>
              <el-tabs v-model="activeMessageType" class="message-tabs" :disabled="currentTask.status === '2'">
                <el-tab-pane label="文本" name="text">
                  <el-form-item label="文本内容" class="content-item">
                    <div class="content-input-wrapper">
                      <el-input
                        v-model="currentMessage.text"
                        type="textarea"
                        :rows="4"
                        placeholder="请输入文本内容"
                        :disabled="currentTask.status === '2'"
                        maxlength="2000"
                        show-word-limit
                      />
                      <div class="emoji-trigger" @click="toggleEmojiPicker">
                        <el-icon class="emoji-icon"><ChatDotRound /></el-icon>
                      </div>
                      <div v-if="showEmojiPicker" ref="emojiPickerRef" class="emoji-picker-container" @click.stop>
                        <EmojiPicker class="emoji-picker" :i18n="zhConfig" @select="onSelectEmoji" />
                      </div>
                    </div>
                  </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="图片" name="image">
                  <el-form-item label="图片上传">
                    <el-upload
                      class="image-uploader"
                      action="#"
                      :auto-upload="false"
                      :show-file-list="false"
                      :on-change="handleImageChange"
                      :on-remove="handleRemoveImage"
                      :on-preview="handlePreviewImage"
                      accept="image/*"
                      :disabled="currentTask.status === '2' || imageUploading"
                    >
                      <div v-if="imageUploading" class="upload-loading-wrapper">
                        <el-icon class="loading-icon is-loading" :size="30"><Loading /></el-icon>
                      </div>
                      <div v-else-if="currentMessage.imageUrl" class="preview-image-wrapper">
                        <img :src="currentMessage.imageUrl" class="preview-image" />
                        <el-icon class="remove-image-icon" @click.stop="handleRemoveImage"><Close /></el-icon>
                      </div>
                      <el-icon v-else class="upload-icon"><Plus /></el-icon>
                    </el-upload>
                  </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="视频" name="video">
                  <el-form-item label="视频上传">
                    <el-upload
                      class="video-uploader"
                      action="#"
                      :auto-upload="false"
                      :show-file-list="false"
                      :on-change="handleVideoChange"
                      accept=".mp4"
                      :disabled="currentTask.status === '2' || videoUploading"
                    >
                      <div v-if="videoUploading" class="upload-loading-wrapper">
                        <el-icon class="loading-icon is-loading" :size="30"><Loading /></el-icon>
                      </div>
                      <div v-else-if="currentMessage.videoUrl" class="preview-video-wrapper">
                        <video :src="currentMessage.videoUrl" class="preview-video" controls />
                        <el-icon class="remove-video-icon" @click.stop="handleRemoveVideo"><Close /></el-icon>
                      </div>
                      <el-icon v-else class="upload-icon"><Plus /></el-icon>
                    </el-upload>
                  </el-form-item>
                </el-tab-pane>
                <!-- <el-tab-pane label="链接" name="link">
                  <el-form-item label="链接地址">
                    <el-input v-model="currentMessage.linkUrl" placeholder="请输入链接地址" :disabled="currentTask.status === '2'" />
                  </el-form-item>
                  <el-form-item label="链接标题">
                    <el-input v-model="currentMessage.linkTitle" placeholder="请输入链接标题" :disabled="currentTask.status === '2'" />
                  </el-form-item>
                  <el-form-item label="链接描述">
                    <el-input v-model="currentMessage.linkDesc" type="textarea" :rows="2" placeholder="请输入链接描述" :disabled="currentTask.status === '2'" />
                  </el-form-item>
                </el-tab-pane> -->
              </el-tabs>
              <div class="message-actions" v-if="currentTask.status !== '2'">
                <el-button type="primary" @click="handleAddMessage">新增单条</el-button>
              </div>
              <div class="message-preview-item-list">
                <div class="preview-title" v-if="messageList.length > 0">
                  已新增消息列表
                  <el-button type="primary" link @click="showMessagePreviewDialog"> </el-button>
                </div>
                <div class="message-preview-item-list">
                  <el-card v-for="(message, index) in messageList" :key="index" class="message-preview-item">
                    <div class="preview-header">
                      <div class="message-info">
                        <span class="message-type-tag" :class="message.type">{{ getMessageTypeLabel(message.type) }}</span>
                        <div class="message-content">
                          <template v-if="message.type === 'text'">
                            {{ message.text }}
                          </template>
                          <template v-else-if="message.type === 'image'">
                            <img :src="message.imageUrl" class="preview-image" />
                          </template>
                          <template v-else-if="message.type === 'video'">
                            <video :src="message.videoUrl" class="preview-video" controls />
                          </template>
                          <template v-else-if="message.type === 'link'">
                            <div class="link-preview">
                              <div class="link-title">{{ message.linkTitle }}</div>
                              <div class="link-url">{{ message.linkUrl }}</div>
                              <div class="link-desc">{{ message.linkDesc }}</div>
                            </div>
                          </template>
                        </div>
                      </div>
                      <div class="preview-actions" v-if="currentTask.status !== '2'">
                        <div class="action-buttons">
                          <el-button type="primary" link :disabled="index === 0" @click="handleMoveMessage(index, 'up')"> </el-button>
                          <el-button type="primary" link :disabled="index === messageList.length - 1" @click="handleMoveMessage(index, 'down')"> </el-button>
                          <el-button type="danger" link @click="handleDeleteMessage(index)"> </el-button>
                        </div>
                      </div>
                    </div>
                  </el-card>
                </div>
              </div>
            </div>
          </div>
          <UserMessagePreview :messages="messageList" />
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editTaskDialogVisible = false">{{ currentTask.status === '2' ? '关闭' : '取消' }}</el-button>
            <el-button type="primary" @click="submitEditTask" v-if="currentTask.status !== '2'">确定</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 消息预览弹窗 -->
      <ZoomInMessagePreview
        v-model="messagePreviewDialogVisible"
        :messages="messageList"
        :readonly="currentTask.status === '2'"
        @move-message="handleMoveMessage"
        @delete-message="handleDeleteMessage"
      />
      <!-- 在template末尾添加弹窗 -->
      <el-dialog v-model="logMessagePreviewDialogVisible" :destroy-on-close="true" width="400px" top="5vh" class="log-message-preview-dialog">
        <div style="width: 100%; height: 80vh; overflow-y: auto">
          <UserMessagePreview :messages="logMessagePreviewList" style="width: 100%; height: 100%" />
        </div>
        <template #footer>
          <el-button @click="logMessagePreviewDialogVisible = false">关闭</el-button>
        </template>
      </el-dialog>
    </div>
  </el-config-provider>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import { ElMessage, ElMessageBox } from 'element-plus';
import FilterForm from '@/components/FilterForm/index.vue';
import Pagination from '@/components/Pagination/index.vue';
import AiWechatInfo from '@/components/AiWechatInfo/index.vue';
import type { FormItem } from '@/components/FilterForm/index.vue';
import {
  getLossCustomerList,
  getLossCustomerMessagingList,
  getLossCustomerTemplateList,
  addLossCustomerTemplate,
  updateLossCustomerTemplate,
  deleteLossCustomerTemplate,
  type LossCustomerMessagingRecord,
  type LossCustomerTemplateRecord,
  addLossCustomerMessaging
} from '@/api/userMange/loseUser';
import { addPrecisionMessaging, updatePrecisionMessaging, deletePrecisionMessaging, uploadFile } from '@/api/userRate/bulkSending';
import ZoomInMessagePreview from '@/components/MessagePreview/ZoomInMessagePreview.vue';
import UserMessagePreview from '@/components/MessagePreview/UserMessagePreview.vue';
import { Plus, ArrowUp, ArrowDown, Delete, ZoomIn, ChatDotRound, Close, Loading } from '@element-plus/icons-vue';
import EmojiPicker from 'vue3-emoji-picker';
import 'vue3-emoji-picker/css';

// --- 类型定义 ---
interface LossCustomer {
  id: string;
  accountCode: string;
  wxUser: { userName: string; userAvatarUrl: string };
  sendWxUser: { userName: string; userAvatarUrl: string; wxAccount: string };
  lastMessage: string;
  lastMessageTime: string;
}

// --- state ---
const activeTab = ref('lossCustomer');
const loading = ref(false);

// 本地存储
const userInfo = reactive(JSON.parse(localStorage.getItem('userInfo') || '{}'));
const msgProfile = reactive(JSON.parse(localStorage.getItem('msgprofile') || '{}'));
const account = userInfo.username || '';
const wxName = ref(msgProfile.wx_id || '');

// 筛选
const filterForm = reactive({
  sendWxName: '',
  taskName: '',
  templateName: ''
});

const formItems = computed<FormItem[]>(() => {
  if (activeTab.value === 'lossCustomer') {
    return [{ label: '客户名称', prop: 'sendWxName', type: 'input', placeholder: '请输入客户名称' }];
  }
  if (activeTab.value === 'activationLog') {
    return [{ label: '任务名称', prop: 'taskName', type: 'input', placeholder: '请输入任务名称' }];
  }
  if (activeTab.value === 'template') {
    return [{ label: '模板名称', prop: 'templateName', type: 'input', placeholder: '请输入模板名称' }];
  }
  return [];
});

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 列表数据
const customerList = ref<LossCustomer[]>([]);
const logList = ref<LossCustomerMessagingRecord[]>([]);
const templateList = ref<LossCustomerTemplateRecord[]>([]);

// 弹窗
const editTaskDialogVisible = ref(false);
const messagePreviewDialogVisible = ref(false);
const selectFriendsDialogVisible = ref(false);
const currentTask = ref<any>({});
const editTaskForm = ref<any>({
  taskName: '',
  friends: [],
  messageData: ''
});
const currentMessage = ref<any>({
  text: '',
  imageUrl: '',
  videoUrl: '',
  linkUrl: '',
  linkTitle: '',
  linkDesc: ''
});
const messageList = ref<any[]>([]);
const activeMessageType = ref('text');
const showEmojiPicker = ref(false);
const emojiPickerRef = ref(null);
const customerTableRef = ref();
const selectedCustomers = ref<any[]>([]);
const isActivateMode = ref(false);
const selectedTemplateId = ref('');
const logMessagePreviewDialogVisible = ref(false);
const logMessagePreviewList = ref<any[]>([]);
const imageUploading = ref(false);
const videoUploading = ref(false);

const zhConfig = {
  search: '搜索',
  categories: {
    recents: '最近使用',
    smileys: '表情',
    people: '人物',
    animals: '动物',
    food: '食物',
    activities: '活动',
    travel: '旅行',
    objects: '物品',
    symbols: '符号',
    flags: '旗帜'
  },
  notFound: '没有找到表情'
};

const onSelectEmoji = (emoji: any) => {
  if (currentMessage.value.text) {
    currentMessage.value.text += emoji.i;
  } else {
    currentMessage.value.text = emoji.i;
  }
  showEmojiPicker.value = false;
};

const parseAndSetMessages = (messageDataString: string) => {
  try {
    const messageDataList = JSON.parse(messageDataString || '[]');
    messageList.value = messageDataList.map((msg: any) => {
      let messageData = msg.data;
      if (msg.type === 'link') {
        try {
          messageData = JSON.parse(msg.data);
        } catch (e) {
          messageData = {};
        }
      }
      switch (msg.type) {
        case 'text':
          return { type: msg.type, text: messageData };
        case 'image':
          return { type: msg.type, imageUrl: messageData };
        case 'video':
          return { type: msg.type, videoUrl: messageData };
        case 'link':
          return { type: msg.type, linkUrl: messageData.url || '', linkTitle: messageData.title || '', linkDesc: messageData.desc || '' };
        default:
          return { type: msg.type };
      }
    });
    if (messageList.value.length > 0) {
      activeMessageType.value = messageList.value[0].type;
    }
  } catch (e) {
    messageList.value = [];
    ElMessage.error('解析模板内容失败');
  }
};

const handleTemplateSelect = (templateId: string) => {
  if (!templateId) {
    messageList.value = [];
    return;
  }
  const selectedTemplate = templateList.value.find((t: any) => t.template_id === templateId);
  if (selectedTemplate) {
    parseAndSetMessages(selectedTemplate.message_data);
  }
};

const fetchTemplates = async () => {
  try {
    const response = await getLossCustomerTemplateList({
      current: 1,
      size: 1000, // a large number to get all templates
      account: account
    });
    if (response.code === 200) {
      templateList.value = response.data.records;
    } else {
      ElMessage.error(response.msg || '获取模板列表失败');
    }
  } catch (error) {
    ElMessage.error('请求模板列表失败');
  }
};

const handleImageChange = async (event: { raw: File }) => {
  const file = event.raw;
  if (file) {
    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      ElMessage.error('只支持图片格式的文件');
      return;
    }

    // 检查文件大小限制（100MB = 100 * 1024 * 1024 bytes）
    const maxSize = 100 * 1024 * 1024; // 100MB
    if (file.size > maxSize) {
      ElMessage.error(`文件大小不能超过100MB，当前文件大小：${(file.size / 1024 / 1024).toFixed(2)}MB`);
      return;
    }

    imageUploading.value = true;
    try {
      const response = await uploadFile(file);
      if (response.data) {
        // 假设接口返回的数据中包含图片URL
        currentMessage.value.imageUrl = (import.meta.env.VITE_GLOB_APP_IMG_URL || '') + response.data;
        ElMessage.success('图片上传成功');
      }
    } catch (error) {
      console.error('图片上传失败:', error);
      ElMessage.error('图片上传失败');
    } finally {
      imageUploading.value = false;
    }
  }
};
const handleRemoveImage = () => {
  currentMessage.value.imageUrl = '';
};
const handlePreviewImage = () => {
  if (currentMessage.value.imageUrl) {
    window.open(currentMessage.value.imageUrl, '_blank');
  }
};
const handleVideoChange = async (event: { raw: File }) => {
  const file = event.raw;
  if (file) {
    // 检查文件类型
    if (!file.type.includes('mp4') && !file.name.toLowerCase().endsWith('.mp4')) {
      ElMessage.error('只支持MP4格式的视频文件');
      return;
    }

    // 检查文件大小限制（100MB = 100 * 1024 * 1024 bytes）
    const maxSize = 100 * 1024 * 1024; // 100MB
    if (file.size > maxSize) {
      ElMessage.error(`文件大小不能超过100MB，当前文件大小：${(file.size / 1024 / 1024).toFixed(2)}MB`);
      return;
    }

    videoUploading.value = true;
    try {
      const response = await uploadFile(file);
      if (response.data) {
        currentMessage.value.videoUrl = (import.meta.env.VITE_GLOB_APP_IMG_URL || '') + response.data;
        ElMessage.success('视频上传成功');
      }
    } catch (error) {
      console.error('视频上传失败:', error);
      ElMessage.error('视频上传失败');
    } finally {
      videoUploading.value = false;
    }
  }
};
const handleRemoveVideo = () => {
  currentMessage.value.videoUrl = '';
};
const handleMiniprogramImageChange = (event: { raw: File }) => {
  // TODO: 实现小程序图片上传逻辑
  currentMessage.value.miniprogramImage = 'mock-miniprogram-image-url';
};
const getMessageTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    text: '文本',
    image: '图片',
    video: '视频',
    link: '链接'
  };
  return typeMap[type] || type;
};

// --- 方法 ---

// 查询
const handleSearch = async () => {
  loading.value = true;
  try {
    let response;
    const commonParams = { current: currentPage.value, size: pageSize.value };
    if (activeTab.value === 'lossCustomer') {
      response = await getLossCustomerList({
        ...commonParams,
        accountCode: account,
        wxName: wxName.value,
        sendWxName: filterForm.sendWxName || undefined
      });
      if (response.code === 200) {
        customerList.value = response.data.records;
        total.value = Number(response.data.total);
      }
    } else if (activeTab.value === 'activationLog') {
      response = await getLossCustomerMessagingList({
        ...commonParams,
        taskName: filterForm.taskName || undefined,
        wxId: wxName.value
      });
      if (response.code === 200) {
        logList.value = response.data.records;
        total.value = Number(response.data.total);
      }
    } else if (activeTab.value === 'template') {
      response = await getLossCustomerTemplateList({ ...commonParams, account: account, templateName: filterForm.templateName || undefined });
      if (response.code === 200) {
        templateList.value = response.data.records;
        total.value = Number(response.data.total);
      }
    }
    if (response && response.code !== 200) ElMessage.error(response.msg || '获取数据失败');
  } catch (error) {
    ElMessage.error('请求失败');
  } finally {
    loading.value = false;
  }
};

// 重置筛选
const resetFilter = () => {
  filterForm.sendWxName = '';
  filterForm.taskName = '';
  filterForm.templateName = '';
  currentPage.value = 1;
  handleSearch();
};

// 分页
const handlePagination = ({ pageNum, pageSize: size }: { pageNum: number; pageSize: number }) => {
  currentPage.value = pageNum;
  pageSize.value = size;
  handleSearch();
};

// 筛选条件变化
const handleFilterChange = (val: any) => {
  Object.assign(filterForm, val);
};

// 切换Tab
const handleTabClick = () => {
  currentPage.value = 1;
  total.value = 0;
  customerList.value = [];
  logList.value = [];
  templateList.value = [];
  resetFilter();
};

// --- 模板操作 ---

const handleAddTask = () => {
  isActivateMode.value = false;
  editTaskDialogVisible.value = true;
  editTaskForm.value = {
    taskName: '',
    friends: [],
    messageData: ''
  };
  messageList.value = [];
  currentMessage.value = {
    text: '',
    imageUrl: '',
    videoUrl: '',
    linkUrl: '',
    linkTitle: '',
    linkDesc: ''
  };
  activeMessageType.value = 'text';
};

const handleEdit = (row: any) => {
  isActivateMode.value = false;
  editTaskDialogVisible.value = true;
  editTaskForm.value = {
    taskName: row.template_name || row.templateName,
    templateId: row.template_id || row.templateId,
    friends: [],
    messageData: row.message_data || row.messageData || ''
  };
  // 解析消息内容
  parseAndSetMessages(row.message_data || row.messageData);
};

const handleDelete = async (row: any) => {
  await ElMessageBox.confirm('确定删除该模板吗?', '提示', { type: 'warning' });
  const res = await deleteLossCustomerTemplate({ templateId: row.template_id || row.templateId });
  if (res.code === 200) {
    ElMessage.success('删除成功');
    handleSearch();
  } else {
    ElMessage.error(res.msg || '删除失败');
  }
};

// --- 精准群发任务操作 ---

const handleAddMessage = () => {
  let isValid = true;
  let errorMessage = '';
  switch (activeMessageType.value) {
    case 'text':
      if (!currentMessage.value.text?.trim()) {
        isValid = false;
        errorMessage = '请输入文本内容';
      }
      break;
    case 'image':
      if (!currentMessage.value.imageUrl) {
        isValid = false;
        errorMessage = '请上传图片';
      }
      break;
    case 'video':
      if (!currentMessage.value.videoUrl) {
        isValid = false;
        errorMessage = '请上传视频';
      }
      break;
    case 'link':
      if (!currentMessage.value.linkUrl?.trim()) {
        isValid = false;
        errorMessage = '请输入链接地址';
      }
      break;
  }
  if (!isValid) {
    ElMessage.warning(errorMessage);
    return;
  }
  // 构造消息对象
  const msg = {
    type: activeMessageType.value,
    ...currentMessage.value
  };
  messageList.value.push(msg);
  // 重置 currentMessage
  currentMessage.value = {
    text: '',
    imageUrl: '',
    videoUrl: '',
    linkUrl: '',
    linkTitle: '',
    linkDesc: ''
  };
  activeMessageType.value = 'text';
};

const handleMoveMessage = (index: number, direction: 'up' | 'down') => {
  const list = messageList.value;
  const newIndex = direction === 'up' ? index - 1 : index + 1;
  if (newIndex < 0 || newIndex >= list.length) return;
  const temp = list[index];
  list[index] = list[newIndex];
  list[newIndex] = temp;
};

const handleDeleteMessage = (index: number) => {
  messageList.value.splice(index, 1);
};

const showMessagePreviewDialog = () => {
  messagePreviewDialogVisible.value = true;
};

const submitEditTask = async () => {
  // 校验
  if (!editTaskForm.value.taskName) {
    ElMessage.warning('请输入模板名称');
    return;
  }
  if (!(activeTab.value === 'template') && editTaskForm.value.friends.length === 0) {
    ElMessage.warning('请选择发送对象');
    return;
  }
  if (messageList.value.length === 0) {
    ElMessage.warning('请新增消息内容');
    return;
  }
  // 组装 messageData
  const messageData = messageList.value.map((msg: any) => {
    let data = '';
    switch (msg.type) {
      case 'text':
        data = msg.text || '';
        break;
      case 'image':
        data = msg.imageUrl || '';
        break;
      case 'video':
        data = msg.videoUrl || '';
        break;
      case 'link':
        data = JSON.stringify({ url: msg.linkUrl, title: msg.linkTitle, desc: msg.linkDesc });
        break;
    }
    return { type: msg.type, data };
  });
  const messageDataStr = JSON.stringify(messageData);

  try {
    let res;
    if (isActivateMode.value) {
      // 激活用户，调用 addLossCustomerMessaging
      res = await addLossCustomerMessaging({
        taskName: editTaskForm.value.taskName,
        messageData: messageDataStr,
        sendWxIds: editTaskForm.value.friends.map((f: any) => f.wx_id).join(','),
        wxId: JSON.parse(localStorage.getItem('msgprofile') || '{}').wx_id || '',
        account: account
      });
      if (res && res.code === 200) {
        ElMessage.success('操作成功');
        editTaskDialogVisible.value = false;
        handleSearch();
      } else {
        ElMessage.error(res.msg || '操作失败');
      }
      return;
    }

    if (editTaskForm.value.templateId) {
      res = await updateLossCustomerTemplate({
        account: account,
        templateId: editTaskForm.value.templateId,
        templateName: editTaskForm.value.taskName,
        messageData: messageDataStr
      });
    } else if (activeTab.value === 'template') {
      res = await addLossCustomerTemplate({
        account: account,
        templateName: editTaskForm.value.taskName,
        messageData: messageDataStr
      });
    } else {
      const taskData = {
        taskName: editTaskForm.value.taskName,
        sendWxIds: editTaskForm.value.friends.map((f: any) => f.wx_id).join(','),
        wxId: JSON.parse(localStorage.getItem('msgprofile') || '{}').wx_id || '',
        messageData: messageDataStr,
        type: 1,
        sendGroupIds: '',
        dateTime: '',
        account: account
      };
      res = await addPrecisionMessaging(taskData);
    }

    if (res && res.code === 200) {
      ElMessage.success('操作成功');
      editTaskDialogVisible.value = false;
      handleSearch();
    } else {
      ElMessage.error((res as any).data.msg || '操作失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败');
  }
};

const toggleEmojiPicker = (event: MouseEvent) => {
  event.stopPropagation();
  // ElMessage.info('表情选择功能正在开发中，敬请期待！');
  showEmojiPicker.value = !showEmojiPicker.value;
};

const onCustomerSelectionChange = (rows: any[]) => {
  selectedCustomers.value = rows;
};

const handleBatchActivateUser = async () => {
  if (!selectedCustomers.value.length) {
    ElMessage.warning('请先勾选要激活的用户');
    return;
  }
  await fetchTemplates();
  isActivateMode.value = true;
  editTaskDialogVisible.value = true;
  selectedTemplateId.value = '';
  editTaskForm.value = {
    taskName: '激活流失用户',
    friends: selectedCustomers.value.map((c: any) => ({
      id: c.sendWxUser?.wxAccount || c.sendWxUser?.id || c.id,
      wx_id: c.sendWxUser?.wxAccount || c.sendWxUser?.id || c.id,
      nick_name: c.sendWxUser?.userName || c.sendWxUser?.nick_name || c.nick_name,
      first_nick_name: c.sendWxUser?.userName || c.sendWxUser?.nick_name || c.nick_name,
      avatar_url: c.sendWxUser?.userAvatarUrl || c.sendWxUser?.avatar_url || c.avatar_url
    })),
    messageData: ''
  };
  messageList.value = [];
  currentMessage.value = {
    text: '',
    imageUrl: '',
    videoUrl: '',
    linkUrl: '',
    linkTitle: '',
    linkDesc: ''
  };
  activeMessageType.value = 'text';
};

const handleRemoveFriend = (friend: any) => {
  if (editTaskForm.value.friends.length <= 1) {
    ElMessage.warning('至少需要保留一位发送对象');
    return;
  }
  editTaskForm.value.friends = editTaskForm.value.friends.filter((f: any) => (f as any).id !== (friend as any).id);
};

const handleSingleActivate = async (row: any) => {
  await fetchTemplates();
  isActivateMode.value = true;
  editTaskDialogVisible.value = true;
  selectedTemplateId.value = '';
  editTaskForm.value = {
    taskName: '激活流失用户',
    friends: [
      {
        id: row.sendWxUser?.wxAccount || row.sendWxUser?.id || row.id,
        wx_id: row.sendWxUser?.wxAccount || row.sendWxUser?.id || row.id,
        nick_name: row.sendWxUser?.userName || row.sendWxUser?.nick_name || row.nick_name,
        first_nick_name: row.sendWxUser?.userName || row.sendWxUser?.nick_name || row.nick_name,
        avatar_url: row.sendWxUser?.userAvatarUrl || row.sendWxUser?.avatar_url || row.avatar_url
      }
    ],
    messageData: ''
  };
  messageList.value = [];
  currentMessage.value = {
    text: '',
    imageUrl: '',
    videoUrl: '',
    linkUrl: '',
    linkTitle: '',
    linkDesc: ''
  };
  activeMessageType.value = 'text';
};

// --- 初始化 ---
onMounted(() => {
  handleSearch();
});

// 暴露方法和变量供 template 使用
// eslint-disable-next-line vue/valid-define-expose
// @ts-ignore
// 解决 template 访问不到 setup 变量的问题
// 只暴露对话框相关方法和变量

defineExpose({
  zhConfig,
  onSelectEmoji,
  handleImageChange,
  handleRemoveImage,
  handlePreviewImage,
  handleVideoChange,
  handleRemoveVideo,
  handleMiniprogramImageChange,
  getMessageTypeLabel,
  handleAddMessage,
  handleMoveMessage,
  handleDeleteMessage,
  showMessagePreviewDialog,
  submitEditTask,
  editTaskDialogVisible,
  messagePreviewDialogVisible,
  selectFriendsDialogVisible,
  currentTask,
  editTaskForm,
  currentMessage,
  messageList,
  activeMessageType,
  showEmojiPicker,
  emojiPickerRef,
  toggleEmojiPicker,
  handleBatchActivateUser,
  isActivateMode,
  handleRemoveFriend,
  getMessageTypes,
  getMessageTypeTag,
  getMessageTypeText,
  selectedTemplateId,
  handleTemplateSelect
});

function getMessageTypes(row: any) {
  let dataStr = row.message_data || row.messageData || '[]';
  let arr: any[] = [];
  try {
    arr = JSON.parse(dataStr);
  } catch {
    return [];
  }
  // 取 type 字段，去重，只保留 text, image, video, link
  return [...new Set(arr.map((msg) => msg.type).filter((type) => ['text', 'image', 'video', 'link'].includes(type)))];
}

function getMessageTypeTag(type: string) {
  switch (type) {
    case 'text':
      return 'info';
    case 'image':
      return 'warning';
    case 'video':
      return 'danger';
    case 'link':
      return 'success';
    default:
      return '';
  }
}

function getMessageTypeText(type: string) {
  switch (type) {
    case 'text':
      return '文本';
    case 'image':
      return '图片';
    case 'video':
      return '视频';
    case 'link':
      return '链接';
    default:
      return type;
  }
}

// 日志内容解析方法
function parseLogMessageData(messageDataString: string) {
  try {
    const messageDataList = JSON.parse(messageDataString || '[]');
    return messageDataList.map((msg: any) => {
      let messageData = msg.data;
      if (msg.type === 'link') {
        try {
          messageData = JSON.parse(msg.data);
        } catch (e) {
          messageData = {};
        }
      }
      switch (msg.type) {
        case 'text':
          return { type: msg.type, text: messageData };
        case 'image':
          return { type: msg.type, imageUrl: messageData };
        case 'video':
          return { type: msg.type, videoUrl: messageData };
        case 'link':
          return { type: msg.type, linkUrl: messageData.url || '', linkTitle: messageData.title || '', linkDesc: messageData.desc || '' };
        default:
          return { type: msg.type };
      }
    });
  } catch (e) {
    return [];
  }
}

function showLogMessagePreview(row: any) {
  // 兼容 messageData 字段名
  const msgData = row.messageData || row.message_data || '';
  logMessagePreviewList.value = parseLogMessageData(msgData);
  logMessagePreviewDialogVisible.value = true;
}
</script>

<style scoped lang="scss">
@use '../userRate/bulkSending/sendmsgdialog.scss';
.loss-customer-container {
  padding: 20px;
  min-height: calc(100vh - 40px);

  .table-section {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .operation-section {
      margin-bottom: 16px;
    }

    .custom-table {
      :deep(.el-table__header) {
        th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: 600;
        }
      }
      :deep(.el-table__row) {
        &:hover {
          td {
            background-color: #f5f7fa;
          }
        }
      }
    }
  }

  .notice-tabs {
    margin-top: 20px;
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  }
}
.remove-image-icon {
  position: absolute;
  top: 2px;
  right: 2px;
  cursor: pointer;
  color: #f56c6c;
  background: #fff;
  border-radius: 50%;
  font-size: 18px;
  z-index: 2;
}
.remove-video-icon {
  position: absolute;
  top: 2px;
  right: 2px;
  cursor: pointer;
  color: #f56c6c;
  background: #fff;
  border-radius: 50%;
  font-size: 18px;
  z-index: 2;
}
.upload-loading-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 120px;
  height: 120px;
}
.loading-icon {
  font-size: 30px;
  color: #409eff;
}
</style>
